import * as Config from '../../config.js';

Component({
  properties: {
    src: {
      type: String,
      value: "",
      observer: function(newVal, oldVal) {
        if (newVal.startsWith("http") || newVal.startsWith("/images")){
          return;
        }
        if (newVal.startsWith("/")) {
          newVal = newVal.substring(1);
        }
        let realSrc = `${Config.baseImageURL}${newVal}`;
        this.setData({
          src: realSrc
        });
      }
    },
    autoheight: {
      type: Boolean,
      value: false
    }
  },

  data: {
    imageStyle: ''
  },

  methods: {
    _onImageLoaded: function(e){
      this.triggerEvent('imgload', e);
      let detail = e.detail || {};
      let width = detail.width || 0; 
      let height = detail.height || 0;
      if (width == 0) {
        return;
      }
      if (!this.data.autoheight) {
        return;
      }
      let query = this.createSelectorQuery();
      query.select('.sd-image').boundingClientRect();
      query.exec((res) => {
        res = res || [];
        if (res.length == 0){
          return;
        }
        let resObj = res[0];
        let queryWidth = resObj.width || 0;
        if (queryWidth == 0) {
          queryWidth = this.screenWidth;
        }
        if (queryWidth == 0) {return;}
        let realHeight = parseInt(queryWidth / width * height);
        this.setData({
          imageStyle: `height:${realHeight}px;`
        });
      });
    },

    _onImageTap: function(e){
      this.triggerEvent('imgtap', e);
    }
  },

  ready: function(){
    this.screenWidth = wx.getSystemInfoSync().screenWidth;
  }
})
